<?php
namespace app\admin\controller;
use think\Request;
use think\Controller;
use app\admin\model;

class MenuManage extends Controller
{

	//实例化model类
	public function oMenu()
	{
		return $oMenu = new model\MenuManage();
	}

	//菜单管理-添加页面
	public function add(){
		return $this->fetch();
	}

	//菜单添加-保存/编辑
	public function saveMenu(Request $request){
		if($_POST){
			if(!isset($_POST['menu_name']) || !$_POST['menu_name']){
				return msg(0, '菜单名称不能为空');
			}
			if(!isset($_POST['menu_module']) || !$_POST['menu_module']){
				return msg(0, '模块不能为空');
			}
			if(!isset($_POST['menu_control']) || !$_POST['menu_control']){
				return msg(0, '控制器不能为空');
			}
			if(!isset($_POST['menu_action']) || !$_POST['menu_action']){
				return msg(0, '方法不能为空');
			}
		}else{
			return msg(0, '提交数据错误');
		}

		//编辑菜单
		if($request->post('edit_mid')){
			return $this->updateMenu($request->post());
		}

		$menuModel = new model\MenuManage();
		$res = $menuModel->insert($_POST);
		if($res){
			return msg(1, '添加菜单成功');
		}else{
			return msg(0, '添加菜单失败');
		}

	}

	//菜单管理-首页
	public function index(Request $request)
	{

		$condition = []; //菜单类型条件

		if($request->get('menu_type') && in_array($request->get('menu_type'), [1, 2])){
			//添加菜单类型条件
			$condition['type'] = intval($request->get('menu_type'));
			$this->assign('menu_type', $condition['type']); //显示搜索选项
		}else{
			$this->assign('menu_type', 0); //显示搜索选项
		}

		//菜单分页
		$menuModel = new model\MenuManage();
		$menuList  = $menuModel->getMenus($condition, 10); //param1:查询条件 param2:显示条数

		$this->assign('menuList', $menuList);
		return $this->fetch('MenuManage');
	}

	//菜单管理-编辑
	public function edit(Request $request)
	{
		$mid = $request->get('mid'); //获取编辑菜单mid

		$menuModel = new model\MenuManage();
		$editMenu  = $menuModel->editMenu($mid);

		$this->assign('editMenu', $editMenu);
		return $this->fetch();
	}

	public function updateMenu($data)
	{
		$mid = $data['edit_mid'];
		$menuModel = new model\MenuManage();

		$res = $menuModel->updateMenuByMid($mid, $data);
		if(0==$res){
			return msg(0, '未编辑任何内容');
		}
		return msg(1, '保存成功');

	}

	//菜单管理-删除
	public function del(Request $request)
	{
		if(!$request->get('mid')){
			return msg(0, '未获取数据ID');
		}
		$mid = $request->get('mid');
		$res = $this->oMenu()->delMenuByMid($mid);
		if(!$res){
			return msg(0, '删除失败');
		}
		return msg(1, '删除成功');
	}

	//菜单管理-排序
	public function order(Request $request)
	{
		$listOrder = $request->post()['list_order'];
		$jump_url  = $_SERVER['HTTP_REFERER'];
		$errors = [];

		if($listOrder){
			foreach($listOrder as $mid=>$val){
				//执行排序
				$mid = $this->oMenu()->listOrderByMid($mid, $val);
				if($mid===false){
					$errors[] = $mid;
				}
			}

			if($errors){
				return msg(0, '更新失败'.implode(',', $errors), ['jump_url', $jump_url]);
			}
			return msg(1, '排序成功', ['jump_url', $jump_url]);
		}
		return msg(1, '排序失败', ['jump_url', $jump_url]);
	}

}